package com.yunduo.module.FileStore.impl;

import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.entity.vo.FileObj;
import com.yunduo.handler.exceptionhandler.OperationException;
import com.yunduo.module.FileStore.FileStore;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;

/**
 * 文件存储到本地
 */
public class LocalFileStore implements FileStore {

    @Value("${yunduo.localFile.path}")
    private String localPath;
    @Value("${yunduo.localFile.domain}")
    private String domain;
    //保存到本地
    @Override
    public String upLoadFile(FileObj file) {
        File path = new File(localPath+"/"+file.getType().getEName());
        if(!path.exists()){
            path.mkdir();
        }
        File mkFile = new File(localPath+"/"+file.getType().getEName()+"/"+file.getName());
        try(FileOutputStream outputStream = new FileOutputStream(mkFile)) {
            outputStream.write(file.getData());
        } catch (Exception e) {
            throw new OperationException(ResultCode.ERROR.getCode(),"上传失败");
        }
        return domain+"/"+file.getType().getEName()+"/"+file.getName();
    }

    //下载文件
    @Override
    public InputStream downloadFile(FileObj file) {
        FileInputStream fileIn;
        try {
            fileIn = new FileInputStream(localPath+"/"+file.getType().getEName()+"/"+file.getName());
        } catch (FileNotFoundException e) {
            throw new OperationException(ResultCode.ERROR.getCode(),"文件下载失败");
        }
        return fileIn;
    }

    //删除文件
    @Override
    public boolean deleteFile(FileObj file) {
        File mkFile = new File(localPath+"/"+file.getType().getEName()+"/"+file.getName());
        return  mkFile.delete();
    }
}
